<?php
namespace app\wechat\controller;

use app\common\controller\AdminBaseController;
use app\wechat\model\WechatMedia as MediaModel;

/**
 * 素材管理
 */
class Media extends AdminBaseController {

	protected $media_model;

	protected function _initialize() {
		parent::_initialize();
		$this -> media_model = new MediaModel();
	}

	/**
	 * 列表
	 * @return mixed
	 */
	public function index() {
		$list = $this -> media_model -> where('mid', 0) -> paginate(15);
		$this -> assign('list', $list);
		return $this -> fetch();
	}

	/**
	 * 添加图片素材
	 * @param string $pid
	 * @return mixed
	 */
	public function add() {
		if ($this -> request -> isPost()) {
			$data = $this -> request -> post();
			$media = load_wechat('Media');
			if (!$data['thumb']) {
				$this -> error('请上传图片');
			}
			// 图片素材
			$path = str_replace('\\', '/', ROOT_PATH) . $data['thumb'];
			$we_data = array('media' => '@' . $path);
			$media_id = $media -> uploadForeverMedia($we_data, 'image');
			if ($media_id === FALSE) {
				$this -> error($media -> errMsg);
			} else {
				$data['media_id'] = $media_id['media_id'];
				$data['url'] = $media_id['url'];
			}
			$data['type'] = 'image';
			$data['mid'] = 0;
			$data['add_time'] = now_time();
			if ($this -> media_model -> allowField(true) -> save($data)) {
				$this -> success('保存成功');
			} else {
				$this -> error('保存失败');
			}
		} else {
			return $this -> fetch();
		}
	}

	/**
	 * 添加图文素材
	 * @param string $pid
	 * @return mixed
	 */
	public function add_news() {
		if ($this -> request -> isPost()) {
			$data = $this -> request -> post();
			$media = load_wechat('Media');
			if (!$data['thumb']) {
				$this -> error('请上传图片');
			}
			// 图片素材
			$path = str_replace('\\', '/', ROOT_PATH) . $data['thumb'];
			$we_data = array('media' => '@' . $path);
			$media_id = $media -> uploadForeverMedia($we_data, 'image');
			if ($media_id === FALSE) {
				$this -> error('更新图片到微信服务器失败');
			} else {
				$data['url'] = $media_id['url'];
			}
			$article = array('title' => input('title'), 'thumb_media_id' => $media_id['media_id'], 'author' => input('author'), 'digest' => input('digest'), 'show_cover_pic' => 0, 'content_source_url' => input('content_source_url'), 'content' => htmlspecialchars_decode(input('content')));
			// 更新到微信服务器
			$articles['articles'][] = $article;
			$media_id = $media -> uploadForeverArticles($articles);
			if ($media_id === FALSE) {
				$this -> error($media -> errMsg);
			} else {
				$data['media_id'] = $media_id['media_id'];
			}
			$data['content'] = json_encode($article);
			$data['type'] = 'news';
			$data['mid'] = 0;
			$data['add_time'] = now_time();
			if ($this -> media_model -> allowField(true) -> save($data)) {
				$this -> success('保存成功');
			} else {
				$this -> error('保存失败');
			}
		} else {
			return $this -> fetch();
		}
	}

	/**
	 * 更新
	 * @param $id
	 */
	public function update_news($id) {
		if ($this -> request -> isPost()) {
			$data = $this -> request -> post();
			$news_model = $this -> media_model -> find($id);
			$news_model['content'] = json_decode($news_model['content'], true);
			$thumb_media_id = $news_model['content']['thumb_media_id'];
			$media = load_wechat('Media');
			if ($data['thumb']) {
				$data2['thumb'] = $data['thumb'];
				// 图片素材
				$path = str_replace('\\', '/', ROOT_PATH) . $data['thumb'];
				$we_data = array('media' => '@' . $path);
				$media_id = $media -> uploadForeverMedia($we_data, 'image');
				if ($media_id === FALSE) {
					$this -> error('更新图片到微信服务器失败');
				} else {
					$data2['url'] = $media_id['url'];
					$thumb_media_id = $media_id['media_id'];
				}
			}
			$article = array('title' => input('title'), 'thumb_media_id' => $thumb_media_id, 'author' => input('author'), 'digest' => input('digest'), 'show_cover_pic' => 0, 'content_source_url' => input('content_source_url'), 'content' => htmlspecialchars_decode(input('content')));
			// 更新到微信服务器
			$articles['articles'] = $article;
			$media_id = $media -> updateForeverArticles($news_model['media_id'], $articles);
			if ($media_id === FALSE) {
				$this -> error($media -> errMsg);
			}
			$data2['name'] = input('name');
			$data2['content'] = json_encode($article);
			$data2['content'] = json_encode($article);
			if ($this -> media_model -> where('id', $id) -> update($data2)) {
				$this -> success('更新成功');
			} else {
				$this -> error('更新失败');
			}
		} else {
			$model = $this -> media_model -> find($id);
			$model['content'] = json_decode($model['content'], true);
			$this -> assign("model", $model);
			return $this -> fetch();
		}
	}

	/**
	 * 删除
	 * @param $id
	 */
	public function delete($id) {
		$model = db('wechat_media') -> find($id);
		$media = load_wechat('Media');
		$result = $media -> delForeverMedia($model['media_id']);
		if ($result === FALSE) {
			$this -> error($media -> errMsg);
		} else {
			if ($this -> media_model -> destroy($id)) {
				$this -> success('删除成功');
			} else {
				$this -> error('删除失败');
			}
		}
	}

	/**
	 * 同步素材库
	 */
	public function lists() {
		$media = load_wechat('Media');
		$types = array('image', 'video', 'voice', 'news');
		$data = array();
		foreach ($types as $type) {
			$lists = $media -> getForeverList($type, 0, 20);
			if ($lists['total_count'] == 0) {
				continue;
			}
			$total_count = $lists['total_count'];
			foreach ($lists['item'] as $item) {
				if ($type == 'news') {
					foreach ($item['content']['news_item'] as $key => $news_item) {
						$sldata = array('mid' => 0, 'name' => $news_item['title'], 'type' => $type, 'media_id' => $item['media_id'], 'add_time' => date('Y-m-d H:i:s', $item['update_time']), 'content' => ($type == 'news') ? json_encode($news_item) : '', );
						$data[] = $sldata;
					}
				} else {
					$sldata = array('mid' => 0, 'name' => $item['name'], 'type' => $type, 'media_id' => $item['media_id'], 'add_time' => date('Y-m-d H:i:s', $item['update_time']), 'url' => isset($item['url']) ? $item['url'] : '', );
					$data[] = $sldata;
				}
			}
			$i = 1;
			$total_count = $total_count - 20;
			while ($total_count > 0) {
				$start = $i * 20 - 1;
				$lists = $media -> getForeverList($type, $start, 20);
				if (!isset($lists['item'])) {
					continue;
				}
				foreach ($lists['item'] as $item) {
					if ($type == 'news') {
						foreach ($item['content']['news_item'] as $key => $news_item) {
							$sldata = array('mid' => 0, 'name' => $news_item['title'], 'type' => $type, 'media_id' => $item['media_id'], 'add_time' => date('Y-m-d H:i:s', $item['update_time']), 'content' => ($type == 'news') ? json_encode($news_item) : '', );
							$data[] = $sldata;
						}
					} else {
						$sldata = array('mid' => 0, 'name' => $item['name'], 'type' => $type, 'media_id' => $item['media_id'], 'add_time' => date('Y-m-d H:i:s', $item['update_time']), 'url' => isset($item['url']) ? $item['url'] : '', );
						$data[] = $sldata;
					}
				}
				$total_count = $total_count - 20;
				$i++;
			}
		}
		$result2 = db() -> query('truncate ' . config('database.prefix') . 'wechat_media');
		$result = $this -> media_model -> insertAll($data);
		if ($result && $result2 !== false) {
			$this -> success('同步素材列表成功', url('media/index'));
		} else {
			$this -> error('同步素材列表失败');
		}
	}

}
